<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="searchObj.data.username" size="medium" placeholder="用户名" class="global-search-box"/>
      <el-input v-model="searchObj.data.real_name" size="medium" placeholder="真实姓名" class="global-search-box"/>
      <el-select v-model="searchObj.data.is_valid" clearable placeholder="是否有效" size="medium" class="global-search-box">
        <el-option value="1" label="有效"/>
        <el-option value="0" label="禁用"/>
      </el-select>
      <el-select v-model="searchObj.data.department" clearable placeholder="请选择部门" size="medium" class="global-search-box">
        <el-option
          v-for="item in depatments"
          :key="item"
          :label="item"
          :value="item"/>
      </el-select>
      <el-button type="primary" size="medium" icon="el-icon-search" @click="getUsers()">搜索</el-button>
      <el-button type="primary" size="medium" @click="reset()">重置</el-button>

      <span class="filter-container-right">
        <el-button v-permission= "{ permissionCode: 'user:scyn' }" type="primary" size="medium" icon="el-icon-plus" @click="syncUsers">同步用户</el-button>
        <el-button v-permission= "{ permissionCode: 'user:forbidden' }" type="danger" size="medium" icon="el-icon-close" @click="forbiddenUsers">禁用用户</el-button>
      </span>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      element-loading-text="Loading"
      fit
      highlight-current-row
      @selection-change="handleSelectChange">
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" label="用户名" sortable prop="loginName" min-width="150"/>
      <el-table-column align="center" label="真实姓名" sortable prop="realName" min-width="120"/>
      <el-table-column align="center" label="部门" prop="department" min-width="160"/>
      <el-table-column align="center" label="邮箱" prop="email" min-width="220"/>
      <el-table-column align="center" label="是否有效" min-width="95">
        <template slot-scope="scope">
          <span :class="scope.row.is_valid === 1 ? 'font-active' : 'font-forbidden'">
            {{ scope.row.is_valid === 1 ? '有效' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后登录日期" prop="last_login_time" min-width="160"/>
      <el-table-column align="center" label="创建日期" sortable prop="create_date" min-width="160"/>
      <el-table-column align="center" label="修改日期" sortable prop="modify_date" min-width="160"/>
      <el-table-column align="center" prop="created_at" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button v-permission= "{ permissionCode: 'user:role' }" type="primary" size="mini" @click="selectRoles(scope.row)">分配角色</el-button>
          <el-button v-permission= "{ permissionCode: 'user:forbidden' }" v-if="scope.row.is_valid === 1" type="danger" size="mini" @click="forbiddenUser(scope.row)">禁用</el-button>
          <el-button v-permission= "{ permissionCode: 'user:active' }" v-else type="success" size="mini" @click="activeUser(scope.row)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogFormVisible" title="分配角色" width="500px">
      <el-select v-model="userRole.roleList" clearable multiple collapse-tags filterable placeholder="请选择角色" style="width: 300px">
        <el-option
          v-for="role in roles"
          :key="role.id"
          :label="role.role_name"
          :value="role.id"/>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="confirmSelectRoles()">确 定</el-button>
      </div>
    </el-dialog>
    <div class="global-paging">
      <el-pagination
        :page-size="10"
        :total="total"
        :page-sizes="[10, 20, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      te: null,
      dialogFormVisible: false,
      list: null,
      listLoading: true,
      total: null,
      depatments: [],
      userRole: {
        roleList: [],
        userId: null
      },
      roles: [],
      validUser: {
        ids: [],
        is_valid: null
      },
      searchObj: {
        currentNo: 1,
        pageSize: 10,
        data: {
          username: '',
          real_name: '',
          department: '',
          is_valid: null
        }
      }
    }
  },
  created() {
    this.getUsers()
    this.getDeptInfo()
  },
  methods: {
    selectRoles(row) {
      this.dialogFormVisible = true
      this.userRole.userId = row.id
      commonApi('/user/queryUserHasRoles', 'post', { userId: row.id }).then(response => {
        if (response.code === 1) {
          this.roles = response.data
          for (let i = 0; i < this.roles.length; i++) {
            if (this.roles[i].hasRole === 1) {
              this.userRole.roleList.push(this.roles[i].id)
            }
          }
        }
      })
    },
    cancel() {
      this.dialogFormVisible = false
      this.userRole.roleList = []
      this.userRole.userId = null
    },
    confirmSelectRoles() {
      commonApi('/user/addRolesForUser', 'post', this.userRole).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '角色分配成功',
            type: 'success'
          })
          this.cancel()
        }
      })
    },
    handleCurrentChange(val) {
      this.searchObj.currentNo = val
      this.getUsers()
    },
    handleSizeChange(val) {
      this.searchObj.pageSize = val
      this.getUsers()
    },
    getUsers() {
      this.listLoading = true
      commonApi('/user/queryUserByCondition', 'post', this.searchObj).then(response => {
        if (response.code === 1) {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    getDeptInfo() {
      commonApi('/user/deptInfo', 'get').then(response => {
        if (response.code === 1) {
          this.depatments = response.data
        }
      })
    },
    syncUsers() {
      commonApi('/sync/userTask', 'get').then(response => {
        if (response.code === 1) {
          this.$message({
            message: '用户同步成功',
            type: 'success'
          })
          this.getUsers()
        }
      })
    },
    activeUser(user) {
      this.$confirm(`确定要启用 用户名为：${user.loginName} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.validUser.ids.push(user.id)
        this.validUser.is_valid = 1
        this.changeUserState()
      }).catch(() => {
      })
    },
    forbiddenUser(user) {
      this.$confirm(`确定要禁用 用户名为：${user.loginName} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.validUser.ids.push(user.id)
        this.validUser.is_valid = 0
        this.changeUserState()
      }).catch(() => {
      })
    },
    forbiddenUsers() {
      if (this.validUser.ids.length === 0) {
        this.$message({
          message: '请选择用户',
          type: 'error'
        })
        return
      }
      this.$confirm(`确定要批量禁用 用户?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.validUser.is_valid = 0
        this.changeUserState()
      }).catch(() => {
      })
    },
    changeUserState() {
      commonApi('/user/disable', 'post', this.validUser).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '用户状态改变成功',
            type: 'success'
          })
          this.getUsers()
        }
        this.validUser.ids = []
        this.validUser.is_valid = null
      })
    },
    reset() {
      for (const index in this.searchObj.data) {
        this.searchObj.data[index] = ''
      }
      this.getUsers()
    },
    handleSelectChange(valArr) {
      this.validUser.ids = []
      for (let i = 0; i < valArr.length; i++) {
        this.validUser.ids.push(valArr[i].id)
      }
    }
  }
}
</script>
<style lang="scss">

</style>
